﻿using Module_Debug.Hardware;
using System;
using System.Collections.Generic;
using System.Drawing;
using System.IO;
using System.IO.Ports;
using System.Text;
using System.Threading;
using System.Windows.Forms;

namespace Module_Debug.x_ViewTrix
{
    public partial class SD4202_Gamma : Form
    {

        CaSDK CaSDKObj = new CaSDK();
        CRC16 CRCData = new CRC16();
        private double[,] D_lums;//目标值-单色
        private double[] D_lum = new double[25];//目标值-白色
        private byte[] Send_buf = new byte[1];
        List<string> lines;
        private byte[] Rec_tmp = new byte[1];
        private byte[] Rec_tmp1 = new byte[1];
        private List<byte> buffer = new List<byte>(4096);//默认分配1/16页内存，并始终限制不允许超过  
        private bool Listening = false;//是否没有执行完invoke相关操作   
        private bool IClosing = false;//是否正在关闭串口，执行Application.DoEvents，并阻止再次invoke  
        //创建类型为Person的对象集合
        List<Setting.Gamma_Property> Diven_Gamma = new List<Setting.Gamma_Property>();
        List<Setting.Offset_Property> Diven_Offset = new List<Setting.Offset_Property>();
        //监听NT37701A挂载
        string[] DBV_SET = { "", "" };
        string[] GAMMA_SET = { "", "" };
        private List<string> ImageType;

        public static bool firstGammaFlag = true;   //初次打开子窗体标志位
        frmMain frmTop = null;

        public SD4202_Gamma(frmMain SX_SD4202)
        {
            frmTop = SX_SD4202;
            InitializeComponent();
            frmTop.Child_window_hide_already = true;
            frmTop.Child_Gamma_Window_Open_Enable = false;//防止重复开启子窗体  

            string[] s = { ".bmp" };
            this.ImageType = new List<string>(s);
        }

        #region   //=================================LCD cfg function:OLED_Show_Click====Start=================
        private void Pattern_Write(byte R_value, byte G_value, byte B_value)
        {
            numPatternR.Value = R_value;
            numPatternG.Value = G_value;
            numPatternB.Value = B_value;
            OLED_Show_Click(btnPatternW, null);
        }

        private void OLED_Show_Click(object sender, EventArgs e)
        {
            byte[] TepArr;
            Button btnTmp = (Button)sender;

            Send_buf = new byte[25];

            Setting.TempRecord.cmdLen = 25;

            Send_buf[0] = 0x0A; //LCD配置标志
            Send_buf[2] = 0x15; //数据长度
            switch (btnTmp.Name)
            {
                case "btnPatternW":                             //写入Pattern参数
                    {
                        Send_buf[1] = 0x07;
                        Send_buf[3] = byte.Parse(numPatternR.Value.ToString());
                        Send_buf[4] = byte.Parse(numPatternG.Value.ToString());
                        Send_buf[5] = byte.Parse(numPatternB.Value.ToString());
                    }
                    break;
                case "btnred":
                    {
                        Send_buf[1] = 0x07;
                        Send_buf[3] = 0xFF;
                        Send_buf[4] = 0;
                        Send_buf[5] = 0;
                    }
                    break; //R
                case "btngreen":
                    {
                        Send_buf[1] = 0x07;
                        Send_buf[3] = 0;
                        Send_buf[4] = 0xFF;
                        Send_buf[5] = 0;
                    }
                    break; //G
                case "btnblue":
                    {
                        Send_buf[1] = 0x07;
                        Send_buf[3] = 0;
                        Send_buf[4] = 0;
                        Send_buf[5] = 0xFF;
                    }
                    break; //B
                case "btnwhite":
                    {
                        Send_buf[1] = 0x07;
                        Send_buf[3] = 0xFF;
                        Send_buf[4] = 0xFF;
                        Send_buf[5] = 0xFF;
                    }
                    break; //W
                case "btnblack":
                    {
                        Send_buf[1] = 0x07;
                        Send_buf[3] = 0;
                        Send_buf[4] = 0;
                        Send_buf[5] = 0;
                    }
                    break; //BL
                default:
                    break;
            }

            CRCData.CalculateCrc16(Send_buf, out Send_buf[23], out Send_buf[24]);
            try
            {
                frmTop.comPort.Write(Send_buf, 0, 25);
            }
            catch
            {
                MessageBox.Show("OLED_Show串口有误，请检查", "错误");
            }



        }


        #endregion //=================================LCD cfg function: OLED_Show_Click====end=================     
        #region  //---VTDR专用界面  打开与否的相关处理  以及 串口 返回数据 处理- --- serial Data----
        private void SD4202_Gamma_FormClosed(object sender, FormClosedEventArgs e)
        {
            ////frmTop.comPort.Close()
            frmTop.comPort.DataReceived -= new SerialDataReceivedEventHandler(SD4202_DataReceived);
            frmTop.comPort.DataReceived += new SerialDataReceivedEventHandler(frmTop.SerialPort1_DataReceived);
            ////frmTop.comPort.Open();
            frmTop.textBox1.Text = frmTop.textBox1.Text + "SD4202_Gamma_FormClosed！\r\n";
            frmTop.Child_Gamma_Window_Open_Enable = true; //允许其他子窗体打开
            frmTop.Child_window_hide_already = false;
            frmTop.IC_comboBox.Enabled = true;
            firstGammaFlag = true;
        }
        private void SD4202_Gamma_VisibleChanged(object sender, EventArgs e)
        {
            if (frmTop.Child_window_hide_already == false) //子窗体已开启标识
            {
                ////frmTop.comPort.Close()
                frmTop.comPort.DataReceived -= new SerialDataReceivedEventHandler(SD4202_DataReceived);
                frmTop.comPort.DataReceived += new SerialDataReceivedEventHandler(frmTop.SerialPort1_DataReceived);
                ////frmTop.comPort.Open();
                frmTop.textBox1.Text = frmTop.textBox1.Text + "SD4202_Gamma_FormHide！\r\n";
                frmTop.Child_window_hide_already = true; //子窗体已隐藏标识
            }
            else
            {
                frmTop.comPort.DataReceived -= new SerialDataReceivedEventHandler(frmTop.SerialPort1_DataReceived);
                frmTop.comPort.DataReceived += new SerialDataReceivedEventHandler(SD4202_DataReceived);
                frmTop.textBox1.Text = frmTop.textBox1.Text + "IC69310_Gamma_FormOpened！\r\n";
                frmTop.Child_window_hide_already = false; //子窗体已开启标识
            }

        }
        private void SD4202_DataReceived(object sender, System.IO.Ports.SerialDataReceivedEventArgs e)//Getting data from Comm Port
        {
            if (IClosing)
            { return; }
            try
            {
                Listening = true;//设置标记，说明我已经开始处理数据，一会儿要使用系统UI的。         
                int n = frmTop.comPort.BytesToRead;
                byte[] buf = new byte[n];
                byte data;
                Setting.TempRecord.cmdLen = n;
                frmTop.comPort.Read(buf, 0, n);//读取缓冲数据     
                bool data_1_catched = false;//缓存记录数据是否捕获到    
                buffer.AddRange(buf);
                byte CRCH, CRCL;
                if (buffer.Count > 3)
                {
                    //RECEIVE
                    // 0x0A: 模组Timing参数 设置  返回
                    // 0x0D: 模组的SSD2828配置数据、DriverIC初始化数据  设置  返回
                    // 0x2F: Demura操作    设置  返回
                    // 0x99: 通用读写、寄存器读写  设置  返回
                    // 0x9E: 功耗测试单元  设置  返回
                    if ((buffer[0] == 0x99) && (Setting.TempRecord.cmdLen > 0))
                    {

                        if (buffer.Count >= Setting.TempRecord.cmdLen)
                        {
                            Rec_tmp = new byte[Setting.TempRecord.cmdLen];
                            byte[] crcTemp = new byte[Setting.TempRecord.cmdLen];
                            buffer.CopyTo(0, crcTemp, 0, Setting.TempRecord.cmdLen);

                            CRCData.CalculateCrc16(crcTemp, out CRCH, out CRCL);
                            if (buffer[Setting.TempRecord.cmdLen - 2] != CRCH && buffer[Setting.TempRecord.cmdLen - 1] != CRCL)     //CRC校验出错
                            {
                                buffer.RemoveRange(0, buffer.Count);
                            }
                            else
                            {
                                buffer.CopyTo(0, Rec_tmp, 0, Setting.TempRecord.cmdLen);//复制一条完整数据到具体的数据缓存   
                                data_1_catched = true;
                                buffer.RemoveRange(0, buffer.Count);  //正确分析一条数据，从缓存中移除数据。  
                            }
                        }
                    }
                    else if ((buffer[0] == 0x6B) && (Setting.TempRecord.cmdLen > 0))
                    {
                        if (buffer.Count >= Setting.TempRecord.cmdLen)
                        {
                            Rec_tmp = new byte[Setting.TempRecord.cmdLen];
                            byte[] crcTemp = new byte[Setting.TempRecord.cmdLen];
                            buffer.CopyTo(0, crcTemp, 0, Setting.TempRecord.cmdLen);
                            CRCData.CalculateCrc16(crcTemp, out CRCH, out CRCL);
                            if (buffer[Setting.TempRecord.cmdLen - 2] != CRCH && buffer[Setting.TempRecord.cmdLen - 1] != CRCL)     //CRC校验出错
                            {
                                buffer.RemoveRange(0, buffer.Count);
                            }
                            else
                            {
                                buffer.CopyTo(0, Rec_tmp, 0, Setting.TempRecord.cmdLen);//复制一条完整数据到具体的数据缓存   
                                data_1_catched = true;
                                buffer.RemoveRange(0, buffer.Count);  //正确分析一条数据，从缓存中移除数据。  
                            }
                        }

                    }
                    else if ((buffer[0] == 0x74) && (Setting.TempRecord.cmdLen > 0))
                    {
                        if (buffer.Count >= Setting.TempRecord.cmdLen)
                        {
                            Rec_tmp = new byte[Setting.TempRecord.cmdLen];
                            byte[] crcTemp = new byte[Setting.TempRecord.cmdLen];
                            buffer.CopyTo(0, crcTemp, 0, Setting.TempRecord.cmdLen);
                            CRCData.CalculateCrc16(crcTemp, out CRCH, out CRCL);
                            if (buffer[Setting.TempRecord.cmdLen - 2] != CRCH && buffer[Setting.TempRecord.cmdLen - 1] != CRCL)     //CRC校验出错
                            {
                                buffer.RemoveRange(0, buffer.Count);
                            }
                            else
                            {
                                buffer.CopyTo(0, Rec_tmp, 0, Setting.TempRecord.cmdLen);//复制一条完整数据到具体的数据缓存   
                                data_1_catched = true;
                                buffer.RemoveRange(0, buffer.Count);  //正确分析一条数据，从缓存中移除数据。  
                            }
                        }

                    }
                    else if (((buffer[0] == 0x1D) || (buffer[0] == 0x0D) || (buffer[0] == 0x0A) || (buffer[0] == 0x2F) || (buffer[0] == 0x99) || (buffer[0] == 0x9e) || (buffer[0] == 0x9f)) && (Setting.TempRecord.cmdLen > 0))
                    {
                        if (buffer.Count >= Setting.TempRecord.cmdLen)
                        {
                            Rec_tmp = new byte[Setting.TempRecord.cmdLen];
                            byte[] crcTemp = new byte[Setting.TempRecord.cmdLen];
                            buffer.CopyTo(0, crcTemp, 0, Setting.TempRecord.cmdLen);

                            CRCData.CalculateCrc16(crcTemp, out CRCH, out CRCL);
                            if (buffer[Setting.TempRecord.cmdLen - 2] != CRCH && buffer[Setting.TempRecord.cmdLen - 1] != CRCL)     //CRC校验出错
                            {
                                buffer.RemoveRange(0, buffer.Count);
                            }
                            else
                            {
                                buffer.CopyTo(0, Rec_tmp, 0, Setting.TempRecord.cmdLen);//复制一条完整数据到具体的数据缓存   
                                data_1_catched = true;
                                buffer.RemoveRange(0, buffer.Count);  //正确分析一条数据，从缓存中移除数据。  
                            }
                        }
                    }

                    else
                        buffer.RemoveRange(0, buffer.Count);
                }
                if (data_1_catched)
                {
                    this.Invoke((EventHandler)(delegate
                    {
                        frmTop.T1.Enabled = false; //停止超时计数
                        if (Rec_tmp[0] == 0x6B) //
                        {
                            switch (Rec_tmp[1])
                            {
                                case 0x01:
                                    {
                                        //  if (Rec_tmp[4] == 0x00)
                                        //     frmTop.textBox1.Text = frmTop.textBox1.Text + "DDIC 寄存器\t写 OK！\r\n";
                                        txttip.Text = String.Format("{0:X2}", Rec_tmp[3]) + "寄存器写OK\r\n";
                                    }
                                    break;
                                case 0x02:
                                    {
                                        string tmp = "";                    //8bit  read
                                        //reText.Text = "";
                                        {
                                            for (int i = 0; i <= (Rec_tmp[4] + 1); i++)
                                            {
                                                if (i == (Rec_tmp[4] + 1))
                                                {
                                                    tmp = tmp + String.Format("{0:X2}", Rec_tmp[i + 3]);//16进制

                                                }
                                                else if (i == 1)
                                                {
                                                    //不显示回读位数
                                                }
                                                else
                                                {
                                                    tmp = tmp + String.Format("{0:X2}", Rec_tmp[i + 3]) + ",";//16进制
                                                }

                                            }
                                        }
                                        // frmTop.Generate_Read_Result_txt.AppendText(tmp + "\r\n");
                                        // reText.Text = tmp;
                                        Application.DoEvents();
                                    }
                                    break;
                                case 0x09:                 //read gamma
                                    {
                                        // if (Rec_tmp[4] == 0x00)
                                        frmTop.textBox1.Text = frmTop.textBox1.Text + "Gamma寄存器Read OK！\r\n";
                                        // frmTop.textBox1.Text = frmTop.textBox1.Text + BitConverter.ToString(Rec_tmp);
                                        int i = 5;
                                        //Array.Copy(Rec_tmp, 5, GammaValueReceived, 0, 150);
                                        for (i = 0; i < 25; i++)
                                        {
                                            GammaValue[i, 0] = (uint)(Rec_tmp[i * 2 + 5] << 8) + Rec_tmp[i * 2 + 6];
                                            GammaValue[i, 1] = (uint)(Rec_tmp[i * 2 + 5 + 50] << 8) + Rec_tmp[i * 2 + 6 + 50];
                                            GammaValue[i, 2] = (uint)(Rec_tmp[i * 2 + 5 + 100] << 8) + Rec_tmp[i * 2 + 6 + 100];
                                        }

                                        for (i = 0; i < 25; i++)
                                        {
                                            DataGirdShow((byte)i, GammaValue[i, 0], GammaValue[i, 1], GammaValue[i, 2]);
                                        }
                                    }
                                    break;
                                case 0x0D:
                                    {
                                        //  if (Rec_tmp[4] == 0x00)
                                        //     frmTop.textBox1.Text = frmTop.textBox1.Text + "DDIC 寄存器\t写 OK！\r\n";
                                        txttip.Text = "gamma OTP OK\r\n";
                                    }
                                    break;
                                default: break;

                            }
                        }
                        else if (Rec_tmp[0] == 0x74)  // PowerTest
                        {
                            int j = 0;
                            for (byte i = 0; i < 25; i++)
                            {
                                if (i == 24)
                                {
                                    GammaValue[24, 0] = (uint)(Convert.ToInt16(Rec_tmp[2 + 25]) + Convert.ToInt16((Rec_tmp[2 + 38] & 0x07) << 8));
                                    GammaValue[24, 1] = (uint)(Convert.ToInt16(Rec_tmp[2 + 63]) + Convert.ToInt16((Rec_tmp[2 + 76] & 0x07) << 8));
                                    GammaValue[24, 2] = (uint)(Convert.ToInt16(Rec_tmp[2 + 101]) + Convert.ToInt16((Rec_tmp[2 + 114] & 0x07) << 8));
                                    break;
                                }
                                //r
                                GammaValue[i, 0] = (uint)(Convert.ToInt16(Rec_tmp[2 + 1 + i]) + Convert.ToInt16((Rec_tmp[2 + 26 + j] & 0x70) << 4));
                                GammaValue[i + 1, 0] = (uint)(Convert.ToInt16(Rec_tmp[2 + 1 + i + 1]) + Convert.ToInt16((Rec_tmp[2 + 26 + j] & 0x07) << 8));
                                //g
                                GammaValue[i, 1] = (uint)(Convert.ToInt16(Rec_tmp[2 + 39 + i]) + Convert.ToInt16((Rec_tmp[2 + 64 + j] & 0x70) << 4));
                                GammaValue[i + 1, 1] = (uint)(Convert.ToInt16(Rec_tmp[2 + 39 + i + 1]) + Convert.ToInt16((Rec_tmp[2 + 64 + j] & 0x07) << 8));
                                //b
                                GammaValue[i, 2] = (uint)(Convert.ToInt16(Rec_tmp[2 + 77 + i]) + Convert.ToInt16((Rec_tmp[2 + 102 + j] & 0x70) << 4));
                                GammaValue[i + 1, 2] = (uint)(Convert.ToInt16(Rec_tmp[2 + 77 + i + 1]) + Convert.ToInt16((Rec_tmp[2 + 102 + j] & 0x07) << 8));
                                i++;
                                j++;
                            }

                            for (byte i = 0; i < 25; i++)
                                DataGirdShow(i, GammaValue[i, 0], GammaValue[i, 1], GammaValue[i, 2]);
                        }
                        //--------------------------------------------Power Test---------------
                        else if (Rec_tmp[0] == 0x9E)  // PowerTest
                        {
                            switch (Rec_tmp[3])
                            {
                                case 0x00:
                                    {
                                    }
                                    break;
                                default:
                                    break;
                            }
                        }
                        //--------------------------------------------Demura----------------------------------------
                        else if (Rec_tmp[0] == 0x2F)  //Demura
                        {
                            switch (Rec_tmp[1])
                            {
                                case 0x01:
                                    {
                                        txttip.Text += "Demura RAM Enable\r\n";
                                    }
                                    break;
                                case 0x0B:
                                    {
                                        txttip.Text += "Demura RAM Addr2 Enable\r\n";
                                    }
                                    break;
                                case 0x0D:
                                    {
                                        txttip.Text += "Demura RAM Addr3 Addr Enable\r\n";
                                    }
                                    break;
                                case 0x0F:
                                    {
                                        txttip.Text += "Demura RAM Addr4 Addr Enable\r\n";
                                    }
                                    break;
                                case 0x02:
                                    {
                                        txttip.Text += "Demura RAM Disable\r\n";
                                    }
                                    break;
                                case 0x03:
                                    {
                                        if (Rec_tmp[4] == 0xff)
                                        {
                                            txttip.Text += "Demura RAM write Flash fail ! \r\n";
                                            // MessageBox.Show("载入失败！");
                                        }
                                        else
                                        {
                                            txttip.Text += Rec_tmp[4].ToString("x2") + "Demura RAM Write Flash Complete ! \r\n";
                                            // MessageBox.Show("载入完成！");
                                        }
                                    }
                                    break;
                                case 0x0A:
                                    {
                                        txttip.Text += Rec_tmp[4].ToString("x2") + "Demura RAM Write Flash2 Complete ! \r\n";
                                        // MessageBox.Show("载入完成！");
                                    }
                                    break;
                                case 0x0C:
                                    {
                                        txttip.Text += Rec_tmp[4].ToString("x2") + "Demura RAM Write Flash3 Complete ! \r\n";
                                        // MessageBox.Show("载入完成！");
                                    }
                                    break;
                                case 0x0E:
                                    {
                                        txttip.Text += Rec_tmp[4].ToString("x2") + "Demura RAM Write Flash4 Complete ! \r\n";
                                        //  MessageBox.Show("载入完成！");
                                    }
                                    break;

                                case 0x04:
                                    {
                                        txttip.Text += "Checksum: " + Rec_tmp[4].ToString("x") + "," + Rec_tmp[5].ToString("x") + "," + Rec_tmp[6].ToString("x") + "," + Rec_tmp[7].ToString("x") + "\r\n";
                                    }
                                    break;
                                case 0x05:
                                    {
                                        txttip.Text += "Flash Erase Success ! \r\n";
                                    }
                                    break;
                                case 0x06:
                                    {
                                        txttip.Text += "flash ID: " + Rec_tmp[4].ToString("x") + "," + Rec_tmp[5].ToString("x") + "," + Rec_tmp[6].ToString("x") + "\r\n";
                                    }
                                    break;
                                case 0x07:
                                    {
                                        txttip.Text += "Demura function on \r\n";
                                    }
                                    break;
                                case 0x08:
                                    {
                                        txttip.Text += "Demura function off \r\n";
                                    }
                                    break;
                                case 0x09:
                                    {
                                        txttip.Text += "Demura OTP complete \r\n";
                                    }
                                    break;
                                default:
                                    break;
                            }
                        }
                        //--------------------------------------------通用读写----------------------------------------------
                        else if (Rec_tmp[0] == 0x99) //GENWR
                        {
                            switch (Rec_tmp[1])
                            {
                                case 0x01:
                                    {
                                        if (Rec_tmp[4] == 0x00)
                                            txttip.Text = txttip.Text + "DDIC 寄存器\t写 OK！\r\n";
                                    }
                                    break;
                                case 0x02:
                                    {
                                        string tmp = "";                    //8bit  read
                                        {
                                            for (int i = 3; i <= (Rec_tmp[2] + 2); i++)
                                            {
                                                if (i == (Rec_tmp[2] + 2))
                                                {
                                                    tmp = tmp + String.Format("{0:X2}", Rec_tmp[i]);//16进制
                                                }
                                                else
                                                {
                                                    tmp = tmp + String.Format("{0:X2}", Rec_tmp[i]) + ",";//16进制
                                                }
                                                // ReadBackarr[i] = Rec_tmp[i];
                                            }
                                            //---------------------Gamma  R --------------------
                                            if ((Rec_tmp[3] == 0xb0) && GammaReadBackFlag)
                                            {
                                                for (int i = 4; i <= (Rec_tmp[2] + 2); i += 2)
                                                {
                                                    GammaValue[(i - 4) >> 1, 0] = (uint)((Rec_tmp[i] << 8) + Rec_tmp[i + 1]);
                                                }
                                            }
                                            else if ((Rec_tmp[3] == 0xb1) && GammaReadBackFlag)
                                            {
                                                for (int i = 4; i <= (Rec_tmp[2] + 2); i += 2)
                                                {
                                                    GammaValue[((i - 4) >> 1) + 8, 0] = (uint)((Rec_tmp[i] << 8) + Rec_tmp[i + 1]);
                                                }
                                            }
                                            else if ((Rec_tmp[3] == 0xb2) && GammaReadBackFlag)
                                            {
                                                for (int i = 4; i <= (Rec_tmp[2] + 2); i += 2)
                                                {
                                                    GammaValue[((i - 4) >> 1) + 16, 0] = (uint)((Rec_tmp[i] << 8) + Rec_tmp[i + 1]);
                                                }
                                            }
                                            else if ((Rec_tmp[3] == 0xb3) && GammaReadBackFlag)
                                            {
                                                for (int i = 4; i <= (Rec_tmp[2] + 2); i += 2)
                                                {
                                                    GammaValue[((i - 4) >> 1) + 24, 0] = (uint)((Rec_tmp[i] << 8) + Rec_tmp[i + 1]);
                                                }
                                            }
                                            //---------------------Gamma  G --------------------
                                            else if ((Rec_tmp[3] == 0xb4) && GammaReadBackFlag)
                                            {
                                                for (int i = 4; i <= (Rec_tmp[2] + 2); i += 2)
                                                {
                                                    GammaValue[(i - 4) >> 1, 1] = (uint)((Rec_tmp[i] << 8) + Rec_tmp[i + 1]);
                                                }
                                            }
                                            else if ((Rec_tmp[3] == 0xb5) && GammaReadBackFlag)
                                            {
                                                for (int i = 4; i <= (Rec_tmp[2] + 2); i += 2)
                                                {
                                                    GammaValue[((i - 4) >> 1) + 8, 1] = (uint)((Rec_tmp[i] << 8) + Rec_tmp[i + 1]);
                                                }
                                            }
                                            else if ((Rec_tmp[3] == 0xb6) && GammaReadBackFlag)
                                            {
                                                for (int i = 4; i <= (Rec_tmp[2] + 2); i += 2)
                                                {
                                                    GammaValue[((i - 4) >> 1) + 16, 1] = (uint)((Rec_tmp[i] << 8) + Rec_tmp[i + 1]);
                                                }
                                            }
                                            else if ((Rec_tmp[3] == 0xb7) && GammaReadBackFlag)
                                            {
                                                for (int i = 4; i <= (Rec_tmp[2] + 2); i += 2)
                                                {
                                                    GammaValue[((i - 4) >> 1) + 24, 1] = (uint)((Rec_tmp[i] << 8) + Rec_tmp[i + 1]);
                                                }
                                            }
                                            //---------------------Gamma  B --------------------
                                            else if ((Rec_tmp[3] == 0xb8) && GammaReadBackFlag)
                                            {
                                                for (int i = 4; i <= (Rec_tmp[2] + 2); i += 2)
                                                {
                                                    GammaValue[(i - 4) >> 1, 2] = (uint)((Rec_tmp[i] << 8) + Rec_tmp[i + 1]);
                                                }
                                            }
                                            else if ((Rec_tmp[3] == 0xb9) && GammaReadBackFlag)
                                            {
                                                for (int i = 4; i <= (Rec_tmp[2] + 2); i += 2)
                                                {
                                                    GammaValue[((i - 4) >> 1) + 8, 2] = (uint)((Rec_tmp[i] << 8) + Rec_tmp[i + 1]);
                                                }
                                            }
                                            else if ((Rec_tmp[3] == 0xbA) && GammaReadBackFlag)
                                            {
                                                for (int i = 4; i <= (Rec_tmp[2] + 2); i += 2)
                                                {
                                                    GammaValue[((i - 4) >> 1) + 16, 2] = (uint)((Rec_tmp[i] << 8) + Rec_tmp[i + 1]);
                                                }
                                            }
                                            else if ((Rec_tmp[3] == 0xbB) && GammaReadBackFlag)
                                            {
                                                for (int i = 4; i <= (Rec_tmp[2] + 2); i += 2)
                                                {
                                                    GammaValue[((i - 4) >> 1) + 24, 2] = (uint)((Rec_tmp[i] << 8) + Rec_tmp[i + 1]);
                                                }
                                            }
                                            GammaReadBackFlag = false;
                                        }
                                        txttip.Text += "DDIC 8bit寄存器--读 OK！\r\n";
                                        txttip.AppendText(tmp + "\r\n");

                                        Application.DoEvents();
                                    }
                                    break;
                                case 0x03:
                                    {
                                        string tmp = "";
                                        tmp = tmp + String.Format("{0:X2}", Rec_tmp[3]) + ",";  //16进制
                                        tmp = tmp + String.Format("{0:X2}", Rec_tmp[4]) + ",";//16进制
                                        tmp = tmp + String.Format("{0:X2}", Rec_tmp[5]);      //16进制

                                        txttip.Text += "DDIC 16bit寄存器--读 OK！\r\n";
                                        txttip.AppendText(tmp + "\r\n");

                                        Application.DoEvents();

                                    }
                                    break;
                                case 0x04:
                                    {
                                        if (Rec_tmp[3] == 0x00)
                                        {
                                            txttip.Text += "vpp off！\r\n";
                                        }
                                        else if (Rec_tmp[3] == 0x01)
                                        {
                                            txttip.Text += "vpp on！\r\n";
                                        }
                                    }
                                    break;
                            }
                        }
                        //----------------------------------------------------------------------------------------------------                       
                        else if (Rec_tmp[0] == 0x9f)    //小黄窗的通用命令读写
                        {
                            txttip.Text += "[" + DateTime.Now.ToLongTimeString().ToString() + "]：" + "命令已执行" + "\r\n";
                            txttip.SelectionStart = this.txttip.Text.Length;
                            txttip.ScrollToCaret();//滚动到光标处
                            if (txttip.Lines.Length > 50) txttip.Text = null;
                        }
                    }));
                }
            }
            finally
            {
                Listening = false;
            }
        }
        static byte[] GetCRCArray(byte[] arr, Byte speedflag)   //处理命令数组，在其头尾增加包头以及CRC校验值，处理后的数据可以直接发送至下位机
        {
            CRC16 CRCData = new CRC16();

            int arrNumbuer;                                                                                                                                                                                                                                                                                                                                             //51
            arrNumbuer = arr.Length;
            arrNumbuer += 6;
            byte[] Send_Datax = new byte[arrNumbuer];
            Send_Datax[0] = 0x9f;
            Send_Datax[1] = (byte)(speedflag << 4);
            Send_Datax[2] = Convert.ToByte(arr.Length + 1);  //为兼容下位机命令，此位置填待传输有效数据长度+1 

            Send_Datax[arr.Length + 3] = 0xFF;  //添加结束标志位
            arr.CopyTo(Send_Datax, 3);//合并数组头 4个Byte 标志位
            //计算校验码                                                 
            CRCData.CalculateCrc16(Send_Datax, out Send_Datax[arrNumbuer - 2], out Send_Datax[arrNumbuer - 1]);
            return Send_Datax;
        }
        #endregion //---串口返回数据处理- --- serial Data----
        private void GR_WriteRead_Click(object sender, EventArgs e)          //上位机使用通用命令读写方式操作DDIC
        {
            string str = regSend.Text.ToString();
            byte DDICReg; byte readnum;
            string[] arr;
            arr = str.Split(',');
            Setting.TempRecord.cmdLen = arr.Length + 5;
            //Send_buf = new byte[Setting.TempRecord.cmdLen];
            //Send_buf[2] = Convert.ToByte(arr.Length);
            Button btnTmp = (Button)sender;
            //Send_buf[0] = 0x6B;

            switch (btnTmp.Name)
            {
                case "writeReg":
                    {
                        String text;
                        text = regSend.Text;
                        frmTop.txtProcessDrivercode(text, out string txtbaseClearOriginal, out string txtMCleatOriginal);
                        if (rBt_LP_DCS_Long_Write.Checked | rBt_LP_DCS_Short_Write.Checked | rBt_LP_Gerneric_Long_Write.Checked | rBt_LP_Gerneric_Short_Write.Checked)
                        {
                            frmTop.SendCmd(0);  //低速
                        }
                        else
                        {
                            frmTop.SendCmd(4); //高速
                        }
                        txttip.Text += "命令已下发...\r\n";
                        txttip.Select(txttip.Text.Length, 0);
                        txttip.ScrollToCaret();
                    }
                    break;
                case "readReg":
                    {
                        //VTDR6100_0XFE_XX = 0x00;
                        //Send_buf[1] = 0x02;
                        DDICReg = byte.Parse(Convert.ToUInt32(arr[0], 16).ToString());
                        try
                        {
                            readnum = byte.Parse(Convert.ToUInt32(arr[1], 16).ToString());
                            frmTop.GeneralRegRead(DDICReg, readnum);
                        }
                        catch
                        {
                            txttip.Text += "读参数异常....\r\n";
                        }

                    }
                    break;

                default:
                    break;
            }
            frmTop.T1.Enabled = false;
            frmTop.T1.Interval = 2000;
            frmTop.T1.Enabled = true;
        }           //上位机使用通用命令读写方式操作DDIC
        private void btnRun_Click(object sender, EventArgs e)   //---复位屏幕，重新点屏
        {
            frmTop.btnRun_Click(frmTop.btnRun, e);
        }
        #region    //---Auto Gamma----------------------
        private void btnSaveGamma_Click(object sender, EventArgs e)
        {

            {
                Button btnTmp = (Button)sender;
                switch (btnTmp.Name)
                {
                    case "btnSaveGamma":
                        {
                            SaveFileDialog sf = new SaveFileDialog();
                            sf.Filter = @"csv文件(*.csv)|*.csv|所有文件(*.*)|*.*"; //定义文件的类型
                            sf.Title = "数据导出";
                            if (sf.ShowDialog() == DialogResult.OK)
                            {
                                FileStream fs = new FileStream(sf.FileName, FileMode.OpenOrCreate, FileAccess.Write);
                                StreamWriter sw = new StreamWriter(fs, Encoding.GetEncoding("GBK"));
                                sw.Write("Num,targetLv,R,G,B\r\n");
                                for (int i = 0; i < Point_SD4202.Length; i++)
                                {
                                    string str = "";
                                    for (int j = 0; j < 5; j++)
                                    {
                                        if (j == 4)
                                        {
                                            str += GammaReg_dataGridView.Rows[i].Cells[j].Value.ToString();
                                            break;

                                        }
                                        str += GammaReg_dataGridView.Rows[i].Cells[j].Value.ToString() + ",";
                                    }
                                    sw.Write(str + "\r\n");
                                }
                                sw.Close();
                                fs.Close();
                            }
                        }
                        break;
                    case "btnLoadGamma":
                        {
                            this.GammaReg_dataGridView.Rows.Clear();
                            OpenFileDialog sf = new OpenFileDialog();
                            int Line_Count = 0;
                            string strtmp = "";
                            sf.Filter = @"csv文件(*.csv)|*.csv|所有文件(*.*)|*.*"; //定义文件的类型
                            sf.Title = "数据导入";
                            if (sf.ShowDialog() == DialogResult.OK) //如果确定保存
                            {
                                FileStream fs = new FileStream(sf.FileName, FileMode.Open, FileAccess.Read);
                                StreamReader streamReader = new StreamReader(fs, Encoding.GetEncoding("GBK"));
                                streamReader.BaseStream.Seek(0, SeekOrigin.Begin);
                                string strLine = streamReader.ReadLine();
                                while (!string.IsNullOrEmpty(strLine))
                                {
                                    strtmp = strtmp + strLine + ",";
                                    strLine = streamReader.ReadLine(); //循环读取下一行
                                    Line_Count++;
                                }
                                fs.Close(); //关闭流
                                streamReader.Close();
                                string[] arrtmp = strtmp.Split(new Char[] { ',' });
                                for (int j = 1; j <= Line_Count - 1; j++)
                                {
                                    DataGridViewRow Row1 = new DataGridViewRow();
                                    GammaReg_dataGridView.Rows.Add(Row1);
                                }
                                try
                                {
                                    for (int i = 0; i < Line_Count - 1; i++)//有一行标题
                                    {
                                        GammaReg_dataGridView.Rows[i].Cells[0].Value = arrtmp[5 * (i + 1) + 0];
                                        GammaReg_dataGridView.Rows[i].Cells[1].Value = arrtmp[5 * (i + 1) + 1];
                                        GammaReg_dataGridView.Rows[i].Cells[2].Value = arrtmp[5 * (i + 1) + 2];
                                        GammaReg_dataGridView.Rows[i].Cells[3].Value = arrtmp[5 * (i + 1) + 3];
                                        GammaReg_dataGridView.Rows[i].Cells[4].Value = arrtmp[5 * (i + 1) + 4];
                                        //------------------------------------
                                        GammaValue[i, 0] = Convert.ToUInt32(arrtmp[(5 * (i + 1)) + 2]);
                                        GammaValue[i, 1] = Convert.ToUInt32(arrtmp[(5 * (i + 1)) + 3]);
                                        GammaValue[i, 2] = Convert.ToUInt32(arrtmp[(5 * (i + 1)) + 4]);
                                    }
                                    MessageBox.Show("数据导入OK！", "提示：");
                                }
                                catch
                                {
                                    MessageBox.Show("数据导入时发生错误！", "提示：");
                                }
                            }
                        }
                        break;
                    case "btn_CAS200_Clean":
                        {
                            DialogResult dr = MessageBox.Show("确认清空列表数据吗？", "系统提示", MessageBoxButtons.OKCancel);
                            if (dr == DialogResult.OK)
                            {
                                this.GammaReg_dataGridView.Rows.Clear();
                            }
                        }
                        break;

                    default: break;
                }
            }
        }
        private byte Gammnum;
        private void SD4202_CGamma_Button_Click(object sender, EventArgs e)   //通过6130 定制命令读取其Gamma值，但此方法因2K平台未适配，故无效
        {
            this.GammaReg_dataGridView.Rows.Clear();
            Send_buf = new byte[157];
            Button btnTmp = (Button)sender;
            Send_buf[0] = 0x6B;
            Send_buf[2] = 0x05; //Length

            Send_buf[3] = Gammnum;
            switch (btnTmp.Name)
            {
                case "SD4202_GammaR":
                    {
                        VTDR6100_0XFE_XX = 0x00;
                        Send_buf[1] = 0x09;
                        Send_buf[4] = 0x96;   //每组gamma数量

                    }
                    break;
                case "SD4202_GammaW":
                    {
                        GammaValueFormat_Click(null, null);
                        byte rh = 1;
                        byte rl = 1;
                        byte gh = 1;
                        byte gl = 1;
                        byte bh = 1;
                        byte bl = 1;

                        GammaValueSet(rh, rl, gh, gl, bh, bl, GammaValueTeparr);
                    }
                    break;
                case "SD4202_OTP":
                    {
                        VTDR6100_0XFE_XX = 0x00;
                        Send_buf[1] = 0x0D;
                        // Send_buf[4] = 0x96;   //每组gamma数量
                    }
                    break;

                default:
                    break;
            }
            Setting.TempRecord.cmdLen = Send_buf[2] + 5;
            CRCData.CalculateCrc16Start_Length(Send_buf, 0, Setting.TempRecord.cmdLen - 2, out Send_buf[Setting.TempRecord.cmdLen - 2], out Send_buf[Setting.TempRecord.cmdLen - 1]);
            try
            {
                frmTop.comPort.Write(Send_buf, 0, Setting.TempRecord.cmdLen);
            }
            catch
            {
                MessageBox.Show("串口有误，请检查", "错误");
            }
            frmTop.T1.Enabled = false;
            frmTop.T1.Interval = 2000;
            frmTop.T1.Enabled = true;
        }

        private double D_x, D_y;
        //private int index = 0;
        private double lum_off, x_off, y_off;
        private double R_x = 0.67;//
        private double R_y = 0.33;
        private double G_x = 0.22;
        private double G_y = 0.71;
        private double B_x = 0.14;
        private double B_y = 0.06;
        private uint[,] GammaValue = new uint[26, 3];//保存当前Gammavalue
        private double auto_lum;  //  存放获取到的产品亮度值
        private double auto_x;
        private double auto_y;        //  存放获取到的产品亮度 色坐标 x,y
        private int index = 1;  //AutoGamma 调整顺序
        private int flag1 = 1;
        private int flag2 = 1;
        private int flag3 = 1;
        bool lastdirupR = true; bool lastdirupG = true; bool lastdirupB = true; // Gamma 调整方向
        private uint step_l = 1;   //Gamma 调节步长
        byte rstep = 16; byte gstep = 16; byte bstep = 16;
        bool STOPAutoGammaFlag = false;     //AutoGamma 停止标志位，解决定时器禁止后AutoGamma无法停止的问题
        byte[] GammaValueTeparr = new byte[54 * 3]; //存放格式化后的GammaValue，以便于直接下发至DDIC
        byte[] ReadBackarr = new byte[32];  //暂存下位机返回数据
        bool GammaReadBackFlag = false; // 下位机返回数据完成标志位
        byte[] GammaValueReceived = new byte[50 * 3]; //存放从下位机接收过来的GammaValue        
        bool ReceivOKFlag = false;
        private int[] Point_SD4202 = new int[25] {//---Gamma绑点数据，这里的数据仅供参考---
            0,1,3,5,7,11,15,19,27,35,43,51,67,83,99,115,131,147,163,179,195,211,227,243,255};
        //byte GPN =  (byte) Point_SD4202.Length; // 获取Gamma绑点数量
        byte GPN = 0; //保存Gamma绑点数量
        private void btnCalGammaValue_Click(object sender, EventArgs e)   //计算对应绑点灰阶值，并连同暂存的Gammavale显示在窗体表格上
        {
            GPN = (byte)Point_SD4202.Length; // 获取Gamma绑点数量
            D_lum = new double[GPN];
            {
                this.GammaReg_dataGridView.Rows.Clear();
            }
            for (byte i = 0; i < GPN; i++)
            {
                D_lum[i] = (Math.Pow((Point_SD4202[i] / 255.0), Convert.ToDouble(txtVT_gamma.Text)) * Convert.ToDouble(txtVT_lum.Text));
                DataGirdShow(i, GammaValue[i, 0], GammaValue[i, 1], GammaValue[i, 2]);
            }
        }
        private void GammaValueFormat_Click(object sender, EventArgs e)   //GammaValue 值拆分成 Byte 并与实际地址进行转换 以便于后续处理发送至下位机
        {
            //R;
            if (NormalGamma.Checked)
            {
                GammaValueTeparr[0] = 0xC0;
            }

            else if (HBMGamma.Checked)
            {
                GammaValueTeparr[0] = 0xC4;
            }
            else if (AODGamma.Checked)
            {
                GammaValueTeparr[0] = 0xC6;
            }

            GammaValueTeparr[1] = 0xF0; //默认
            for (int i = 0; i < 25; i++)//R
            {
                // txtGammadisplay.Text += "," + Convert.ToString(GammaValue[i, 0] >> 8, 16) + "," + Convert.ToString(GammaValue[i, 0] & 0xff, 16);  
                GammaValueTeparr[i + 2] = (byte)(GammaValue[i, 0] & 0xff);
            }
            for (int i = 0; i < 12; i++)
            {
                // txtGammadisplay.Text += "," + Convert.ToString(GammaValue[i, 0] >> 8, 16) + "," + Convert.ToString(GammaValue[i, 0] & 0xff, 16);  
                GammaValueTeparr[i + 27] = (byte)(((GammaValue[2 * i, 0] >> 8) & 0x07) << 4 | ((GammaValue[2 * i + 1, 0] >> 8) & 0x07));
            }
            GammaValueTeparr[39] = (byte)((GammaValue[24, 0] >> 8) & 0x07);
            //G
            for (int i = 0; i < 25; i++)
            {
                // txtGammadisplay.Text += "," + Convert.ToString(GammaValue[i, 0] >> 8, 16) + "," + Convert.ToString(GammaValue[i, 0] & 0xff, 16);  
                GammaValueTeparr[i + 40] = (byte)(GammaValue[i, 1] & 0xff);
            }
            for (int i = 0; i < 12; i++)
            {
                // txtGammadisplay.Text += "," + Convert.ToString(GammaValue[i, 0] >> 8, 16) + "," + Convert.ToString(GammaValue[i, 0] & 0xff, 16);  
                GammaValueTeparr[i + 65] = (byte)(((GammaValue[2 * i, 1] >> 8) & 0x07) << 4 | ((GammaValue[2 * i + 1, 1] >> 8) & 0x07));
            }
            GammaValueTeparr[77] = (byte)((GammaValue[24, 1] >> 8) & 0x07);
            //B
            for (int i = 0; i < 25; i++)
            {
                // txtGammadisplay.Text += "," + Convert.ToString(GammaValue[i, 0] >> 8, 16) + "," + Convert.ToString(GammaValue[i, 0] & 0xff, 16);  
                GammaValueTeparr[i + 78] = (byte)(GammaValue[i, 2] & 0xff);
            }
            for (int i = 0; i < 12; i++)
            {
                // txtGammadisplay.Text += "," + Convert.ToString(GammaValue[i, 0] >> 8, 16) + "," + Convert.ToString(GammaValue[i, 0] & 0xff, 16);  
                GammaValueTeparr[i + 103] = (byte)(((GammaValue[2 * i, 2] >> 8) & 0x07) << 4 | (GammaValue[2 * i + 1, 2] >> 8) & 0x07);
            }
            GammaValueTeparr[115] = (byte)((GammaValue[24, 2] >> 8) & 0x07);

        }
        private void GammaValueSet(byte rh, byte rl, byte gh, byte gl, byte bh, byte bl, byte[] Gammaarr)  //把拆分后Gamma值按照DDIC 规定格式排列后送入DDIC
        {   //通过高速方式向第一条Gamma写入一组Gamma值
            byte[] TepArr;
            try
            {

                //-------------default----  
                TepArr = new byte[] {
                 0x74,0xc0,0x70,0x00,0x61,0x92,0xbd,0xe6,0x26,0x59,0x81,0xc2,0xf7,0x25,0x4e,0x95,0xd2,0x0b,0x42,0x77,0xab,0xdf,0x15,
                    0x4b,0x87,0xc2,0x00,0x30,0x01,0x11,0x12,0x22,0x22,0x33,0x33,0x44,0x44,0x45,0x55,0x56,0x06,0x00,0x49,0x6b,0x90,0xb5,
                    0xf0,0x20,0x46,0x84,0xb6,0xe1,0x06,0x47,0x80,0xb4,0xe4,0x14,0x42,0x71,0xa0,0xd1,0x02,0x37,0x6f,0x9d,0x01,0x11,0x11,0x22,
                    0x22,0x23,0x33,0x33,0x44,0x44,0x45,0x55,0x05,0x00,0xac,0xd6,0x00,0x29,0x6a,0xa0,0xca,0x0d,0x44,0x72,0x9a,0xe1,0x21,0x5a,0x91,
                    0xc7,0xfb,0x31,0x67,0x9f,0xd9,0x17,0x56,0x87,0x01,0x12,0x22,0x22,0x33,0x33,0x34,0x44,0x44,0x55,0x55,0x66,0x06
                };

                Array.Copy(Gammaarr, 0, TepArr, 1, 116);

                frmTop.comPort.Write(GetCRCArray(TepArr, 4), 0, TepArr.Length + 6);//循环部分，每段数据结尾
                //Application.DoEvents();//重点，必须加上，否则父子窗体都假死
            }
            catch
            {
                txttip.Text += "串口问题Gamma无法写入，请检查" + "'\r\n";
                txttip.Focus();//获取焦点
                txttip.Select(txttip.TextLength, 0);//光标定位到文本最后
                txttip.ScrollToCaret();//滚动到光标处
                txttip.ForeColor = Color.OrangeRed;
                return;
            }
        }
        private void btnAutoGammas_SD4202_Click(object sender, EventArgs e)
        {
            int flag = 1;
            txttip.ForeColor = Color.Black;
            STOPAutoGammaFlag = false;
            GPN = (byte)Point_SD4202.Length; // 获取Gamma绑点数量
            double Lr_d, Lg_d, Lb_d;
            D_lums = new double[GPN, 3];
            D_lum = new double[GPN];
            index = (int)indexS.Value;  //Gamma绑点序号，第一个绑点通常对应255灰阶
            flag1 = flag2 = flag3 = 1;
            rstep = 16;
            gstep = 16;
            bstep = 16;
            txttip.Text += "GammaValue最大值被限定为: " + GammaValueMax + "\r\n";
            TimTest.Start();
            TimeNow = DateTime.Now; //开始计时

            for (int i = 0; i < GPN; i++)  //计算相应绑点对应的亮度值
            {
                D_lum[i] = (Math.Pow((Point_SD4202[i] / 255.0), Convert.ToDouble(txtVT_gamma.Text)) * Convert.ToDouble(txtVT_lum.Text));
            }

            D_x = Convert.ToDouble(txtVT_x.Text);  //获取调节目标色坐标 x
            D_y = Convert.ToDouble(txtVT_y.Text); ////获取调节目标色坐标 y
            Lr_d = R_y * ((D_y - G_y) * (B_x - D_x) + (D_x - G_x) * (D_y - B_y)) / B_y / ((D_y - G_y) * (D_x - R_x) + (D_x - G_x) * (R_y - D_y));
            Lb_d = 1.0;
            Lg_d = G_y * ((D_y - R_y) * (B_x - D_x) + (D_x - R_x) * (D_y - B_y)) / B_y / ((D_y - R_y) * (D_x - G_x) + (D_x - R_x) * (G_y - D_y));

            for (int i = 0; i < GPN; i++)   // 通过色坐标已经亮度计算各绑点R/G/B分量对应的亮度值
            {
                D_lums[i, 0] = D_lum[i] * Lr_d / (Lr_d + Lg_d + Lb_d);
                D_lums[i, 1] = D_lum[i] * Lg_d / (Lr_d + Lg_d + Lb_d);
                D_lums[i, 2] = D_lum[i] * Lb_d / (Lr_d + Lg_d + Lb_d);
            }
            labTargetlum.Text = "Tar:" + D_lum[GPN - index].ToString("f4"); ;   //显示当前绑点对应的目标亮度值
            switch (flag)
            {
                case 1://寄存器值与亮度正比
                    {
                        //lum_off = Convert.ToDouble(txtVT_loff.Text);
                        x_off = Convert.ToDouble(txtVT_xoff.Text);   //获取色坐标允差范围
                        y_off = Convert.ToDouble(txtVT_yoff.Text);
                        numPatternR.Value = Point_SD4202[GPN - index];     //设定绑点灰阶
                        numPatternG.Value = Point_SD4202[GPN - index];
                        numPatternB.Value = Point_SD4202[GPN - index];
                        OLED_Show_Click(btnPatternW, e);       //显示255白画面，从255白画面开始调节
                        Thread.Sleep(10);
                        Msr_CA310();
                        Msr_CA310(); //修复讨厌的灰阶跳变时CA410数据异常的问题
                        ReceivOKFlag = false;
                        T17.Enabled = true;   //通过T17定时器进行Gamma调整
                    }
                    break;
                case 2:  //寄存器值与亮度反比
                    break;
                default:
                    break;
            }
        }
        private void Msr_CA310()
        {
            frmTop.Msr_CASDK();
            auto_lum = frmTop.CASDK_LUM;
            auto_x = frmTop.CASDK_x;
            auto_y = frmTop.CASDK_y;
        }   //获取CA310/CA410读数
        private void btnAutoGammaJumpTest_Click(object sender, EventArgs e)
        {
            JumpGammaAdjustFlag = true;
        }
        bool JumpGammaAdjustFlag = false;  //跳过某个绑点标志位，通常用于末尾低灰阶
        UInt32 timeout = 0;
        private void T17_Tick(object sender, EventArgs e)   //AutoGamma处理过程
        {
            double Lr_t, Lg_t, Lb_t, lumr, lumg, lumb;
            T17.Enabled = false;
            T17.Interval = 20;  //不能过短，要给显示画面一个稳定的时间

            Msr_CA310();
            txtlvshow.Text = "Lv: " + auto_lum.ToString("f4") + "\r\n" + "x: " + auto_x.ToString("f4") + "\r\n" + "y: " + auto_y.ToString("f4") + "\r\n";
            labTargetlum.Text = "Tar:" + D_lum[GPN - index].ToString("#0.00000");  // 在UI上显示当前绑点的目标亮度值
            txttip.Text += "Adjust inex:" + GPN + "----" + index + "\r\n";

            lum_off = (D_lum[GPN - index] * Convert.ToDouble(numVT_loff.Value) / 1000);  //计算当前绑点允许的亮度误差范围
            x_off = Convert.ToDouble(txtVT_xoff.Text);
            y_off = Convert.ToDouble(txtVT_yoff.Text);       //获取色坐标允许误差范围

            if (index > 20)  //根据灰阶范围修正色坐标误差范围
            {   //根据灰阶范围修正色坐标误差范围
                if (D_lum[GPN - 1] < 10)
                {
                    x_off += x_off * 4;
                    y_off += y_off * 4;
                }
                else if (D_lum[GPN - 1] < 30)
                {
                    {
                        x_off += x_off * 3;
                        y_off += y_off * 3;
                    }
                }
                else if (D_lum[GPN - 1] < 90)
                {
                    {
                        x_off += x_off * 2;
                        y_off += y_off * 2;
                    }
                }
                else
                {
                    {
                        x_off += x_off;
                        y_off += y_off;
                    }
                }
            } //根据灰阶范围修正色坐标误差范围

            if ((auto_lum < (D_lum[GPN - index] + lum_off)) && (auto_lum > (D_lum[GPN - index] - lum_off)))//
                flag1 = 0;  //判断亮度以及色坐标是否在目标范围
            if ((auto_y < (D_y + y_off)) && (auto_y > (D_y - y_off)) && flag1 == 0)//
                flag2 = 0;  //判断亮度以及色坐标是否在目标范围
            if ((auto_x < (D_x + x_off)) && (auto_x > (D_x - x_off)) && flag1 == 0)//
                flag3 = 0;  //判断亮度以及色坐标是否在目标范围
            if ((flag1 == 0 && flag2 == 0 && flag3 == 0) && (index < 10)) //低灰阶本来就很难调就不这么折腾了
            {   //初次判断调整OK后，再来复测一次，以消除偶发调不准问题
                Msr_CA310();
                if ((auto_lum < (D_lum[GPN - index] + lum_off)) && (auto_lum > (D_lum[GPN - index] - lum_off)))//
                    flag1 = 0;  //判断亮度以及色坐标是否在目标范围
                else flag1 = 1;
                if ((auto_y < (D_y + y_off)) && (auto_y > (D_y - y_off)) && flag1 == 0)//
                    flag2 = 0;  //判断亮度以及色坐标是否在目标范围
                else flag2 = 1;
                if ((auto_x < (D_x + x_off)) && (auto_x > (D_x - x_off)) && flag1 == 0)//
                    flag3 = 0;  //判断亮度以及色坐标是否在目标范围
                else flag3 = 1;
            }//初次判断调整OK后，再来复测一次，以消除偶发调不准问题,

            Lr_t = R_y * ((auto_y - G_y) * (B_x - auto_x) + (auto_x - G_x) * (auto_y - B_y)) / B_y / ((auto_y - G_y) * (auto_x - R_x) + (auto_x - G_x) * (R_y - auto_y));
            Lb_t = 1.0;
            Lg_t = G_y * ((auto_y - R_y) * (B_x - auto_x) + (auto_x - R_x) * (auto_y - B_y)) / B_y / ((auto_y - R_y) * (auto_x - G_x) + (auto_x - R_x) * (G_y - auto_y));
            lumr = auto_lum * Lr_t / (Lr_t + Lg_t + Lb_t);
            lumg = auto_lum * Lg_t / (Lr_t + Lg_t + Lb_t);
            lumb = auto_lum * Lb_t / (Lr_t + Lg_t + Lb_t);

            if (((flag1 == 0 && flag2 == 0 && flag3 == 0) || JumpGammaAdjustFlag) || (timeout > 3 * numTurnGammaTimeout.Value))
            {
                if (timeout > 3 * numTurnGammaTimeout.Value) { txttip.Text = "--模糊处理--\r\n" + "----模糊处理----\r\n" + "--------模糊处理--------\r\n" + "----模糊处理----\r\n" + "--模糊处理--\r\n"; }
                timeout = 0;
                index++;
                if (index == GPN)   //  最后一个绑点通常为0，不用调试结束即可
                {
                    TimTest.Stop();//停止计时
                    txttip.Text = txttip.Text + "VTDR6100 gamma调试完毕!\r\n";
                    txttip.Focus();//获取焦点
                    txttip.Select(txttip.TextLength, 0);//光标定位到文本最后
                    txttip.ScrollToCaret();//滚动到光标处
                    STOPAutoGammaFlag = true;
                    btn_VTDR6100_Stop.PerformClick();
                    return;
                }
                if (index < GPN)
                {
                    txttip.Text += index + "完成...\r\n";
                    txttip.Select(txttip.Text.Length, 0);
                    txttip.ScrollToCaret();    //上滚提示信息以便于查看
                    for (int i = 0; i < 25; i++)    //本意用于显示当前绑点目标信息，但一般用不到
                    {
                        //Convert.ToString(要转的数, 16);//string s = string.Format("0x{0:X2}", i);    // s = 0x0F;
                        //Points_LV.Text += (i + 1) + ",R/G/B, V" + Point_SD4202[24 - i] + ": " + string.Format("0x{0:X2}", GammaValue[24 - i, 0]) + "--";
                        //Points_LV.Text += string.Format("0x{0:X2}", GammaValue[24 - i, 1]) + "--";
                        //Points_LV.Text += string.Format("0x{0:X2}", GammaValue[24 - i, 2]) + "\r\n";

                        //this.GammaReg_dataGridView.Rows.Clear();
                        //DataGirdShow((byte)i, GammaValue[i, 0], GammaValue[i, 1], GammaValue[i, 2]);
                        //Points_LV.Text += (i + 1) + ",R/G/B, V" + Point_SD4202[24 - i] + ": " + string.Format("0x{0:X2}", GammaValue[24 - i, 0]) + "--";
                        //Points_LV.Text += string.Format("0x{0:X2}", GammaValue[24 - i, 1]) + "--";
                        //Points_LV.Text += string.Format("0x{0:X2}", GammaValue[24 - i, 2]) + "\r\n";
                    }
                    //Thread.Sleep(10); //1秒=1000毫秒，
                    //T17.Enabled = true;
                    flag1 = 1;  //复位 亮度色坐标符合目标标志位
                    flag2 = 1;
                    flag3 = 1;
                    JumpGammaAdjustFlag = false;
                }
                rstep = (byte)(int.Parse(numStep.Value.ToString())); ;    //重新获取调节步长
                gstep = (byte)(int.Parse(numStep.Value.ToString())); ;
                bstep = (byte)(int.Parse(numStep.Value.ToString())); ;
                numPatternR.Value = Point_SD4202[GPN - index];     //设定绑点灰阶
                numPatternG.Value = Point_SD4202[GPN - index];
                numPatternB.Value = Point_SD4202[GPN - index];
                OLED_Show_Click(btnPatternW, e);//写入Pattern参数   ，显示帮点对应灰阶画面
                //ReceivOKFlag = false;
                Thread.Sleep(10);
                Msr_CA310();
                Msr_CA310(); //修复讨厌的灰阶跳变时CA410数据异常的问题
                if (!STOPAutoGammaFlag)
                    T17.Enabled = true;
            }
            else
            {
                if ((GPN - index == 1) | (GPN - index == 2))//这里index最大值为绑点数量-1；倒数第2个绑点 以及倒数第3个绑点可以做技术处理
                {
                    //GammaValue[0, 1] = 0;  //0绑点不调，直接送零
                    //GammaValue[0, 2] = 0;
                    //GammaValue[0, 0] = 0;
                    GammaValue[GPN - index, 0] = GammaValue[GPN - index + 1, 0] >> 1;  //绑点不调，直接赋值算了，如果有过度不均再手动修正即可
                    GammaValue[GPN - index, 1] = GammaValue[GPN - index + 1, 1] >> 1;
                    GammaValue[GPN - index, 2] = GammaValue[GPN - index + 1, 2] >> 1;
                    JumpGammaAdjustFlag = true;
                }
                //else if (GPN - index == 2) //倒数第2个绑点
                //{
                //}
                else
                {
                    if ((flag3 == 1) | (flag2 == 1) | (flag1 == 1))   //这个判断的意义可以猜猜看
                    {
                        {   //Gamma --R----
                            if (lumr > D_lums[GPN - index, 0])
                            {
                                if ((!lastdirupR)) { timeout++; }
                                if ((!lastdirupR) && (rstep >= 2)) rstep >>= 1;
                                GammaValue[GPN - index, 0] = GammaValue[GPN - index, 0] - rstep;// (byte)(int.Parse(numStep.Value.ToString()));
                                lastdirupR = true;
                            }
                            else
                            {
                                if ((lastdirupR)) { timeout++; }
                                if ((lastdirupR) && (rstep >= 2)) rstep >>= 1;
                                GammaValue[GPN - index, 0] = GammaValue[GPN - index, 0] + rstep;
                                lastdirupR = false;
                            }
                        }
                        {//Gamma ---G--
                            if (lumg > D_lums[GPN - index, 1])
                            {
                                if ((!lastdirupG)) { timeout++; }
                                if ((!lastdirupG) && (gstep >= 2)) gstep >>= 1;
                                GammaValue[GPN - index, 1] = GammaValue[GPN - index, 1] - gstep;
                                lastdirupG = true;
                            }
                            else
                            {
                                if ((lastdirupG)) { timeout++; }
                                if ((lastdirupG) && (gstep >= 2)) gstep >>= 1;
                                GammaValue[GPN - index, 1] = GammaValue[GPN - index, 1] + gstep;
                                lastdirupG = false;
                            }
                        }
                        {//--Gamma  ---B---
                            if (lumb > D_lums[GPN - index, 2])
                            {
                                if ((!lastdirupB)) { timeout++; }
                                if ((!lastdirupB) && (bstep >= 2)) bstep >>= 1;
                                GammaValue[GPN - index, 2] = GammaValue[GPN - index, 2] - bstep;
                                lastdirupB = true;
                            }
                            else
                            {
                                if ((lastdirupB)) { timeout++; }
                                if ((lastdirupB) && (bstep >= 2)) bstep >>= 1;
                                GammaValue[GPN - index, 2] = GammaValue[GPN - index, 2] + bstep;
                                lastdirupB = false;
                            }
                        }
                        txttip.Text += "rstep:" + rstep + "gstetp:" + gstep + "bstep:" + bstep + "\r\n";
                        txttip.Select(txttip.Text.Length, 0);
                        txttip.ScrollToCaret();
                    }   //如果Gamma Value不在目标范围内，此处修正之
                    CheckandCorrectGammaValue();
                    GammaValueFormat_Click(null, null);
                    //显示当前(待)写入的Gamma寄存器值
                    txtGammaValue.Text = GammaValue[GPN - index, 0] + "\r\n" + GammaValue[GPN - index, 1] + "\r\n" + GammaValue[GPN - index, 2] + "\r\n";
                    GammaValueSet(1, 1, 1, 1, 1, 1, GammaValueTeparr);
                    Thread.Sleep(20);
                    Application.DoEvents();//重点，必须加上，否则父子窗体都假死                            
                }
                if (!STOPAutoGammaFlag)
                    T17.Enabled = true;
            }

        }

        private void btnVTStop_Click(object sender, EventArgs e)
        {
            T7.Enabled = false;
            STOPAutoGammaFlag = true;
            flag1 = 1;
            flag2 = 1;
            flag3 = 1;
            TimTest.Stop();//停止计时
            txttip.ForeColor = Color.Black;
            btnCalculateSD4202.PerformClick();
        }
        uint GammaValueMax = 0x7ff - 1;
        private void CheckandCorrectGammaValue()   //检查GammaValue 是否按照大小排列
        {
            byte i; GPN = (byte)Point_SD4202.Length; // 获取Gamma绑点数量
            if (GammaValue[GPN - 1, 0] > GammaValueMax)
            {
                GammaValue[GPN - 1, 0] = GammaValueMax - 16;
            }
            if (GammaValue[GPN - 1, 1] > GammaValueMax)
            {
                GammaValue[GPN - 1, 1] = GammaValueMax - 16;
            }
            if (GammaValue[GPN - 1, 2] > GammaValueMax)
            {
                GammaValue[GPN - 1, 2] = GammaValueMax - 16;
            }  //确保GammaValue不要超过DDIC 中Gamma寄存能接受的最大值


            for (i = (byte)(GPN - 1); i > 0; i--)    //低灰阶GammaValue如果大于高灰阶GammaValue则强制变小
            {
                if (GammaValue[i, 0] < GammaValue[i - 1, 0])
                {
                    GammaValue[i - 1, 0] = GammaValue[i, 0] - 0;
                    //GammaValueFormat_Click(null, null);
                }
                if (GammaValue[i, 1] < GammaValue[i - 1, 1])
                {
                    GammaValue[i - 1, 1] = GammaValue[i, 1] - 0;
                    //GammaValueFormat_Click(null, null);
                }
                if (GammaValue[i, 2] < GammaValue[i - 1, 2])
                {
                    GammaValue[i - 1, 2] = GammaValue[i, 2] - 0;
                    //GammaValueFormat_Click(null, null);
                }
            }
            GammaValue[0, 0] = 0; GammaValue[0, 1] = 0; GammaValue[0, 2] = 0;
            if (chkGammaGridViewFresh.Checked)   // 刷新UI界面GammaValue值显示
            {
                this.GammaReg_dataGridView.Rows.Clear();
                for (i = 0; i < GPN; i++)
                {
                    DataGirdShow(i, GammaValue[i, 0], GammaValue[i, 1], GammaValue[i, 2]);
                }
            }
        }
        private void btnGammaValueUpdate_Click(object sender, EventArgs e)      //刷新UI上表格内的Gamma数据
        {
            int Line_Count = 0;
            try
            {
                Line_Count = GammaReg_dataGridView.RowCount;
            }
            catch
            {
                MessageBox.Show("表格数据(行数)异常！", "提示：");
                return;
            }
            try
            {
                for (int i = 0; i < Line_Count - 1; i++)//有一行标题
                {
                    GammaValue[i, 0] = Convert.ToUInt32(GammaReg_dataGridView.Rows[i].Cells[2].Value);
                    GammaValue[i, 1] = Convert.ToUInt32(GammaReg_dataGridView.Rows[i].Cells[3].Value);
                    GammaValue[i, 2] = Convert.ToUInt32(GammaReg_dataGridView.Rows[i].Cells[4].Value);
                }
                //MessageBox.Show("数据更新OK！", "提示：");
                txttip.Text += "Gamma数据更新OK！\r\n";
                CheckandCorrectGammaValue();   //检查Gamma 是否存在高低灰阶数值错乱 ,并刷新表格数据              
                GammaValueFormat_Click(null, null);  //Gamma 值与实际地址进行转换 
                GammaValueSet(0, 0, 0, 0, 0, 0, GammaValueTeparr); //GammaValue 转换成特定格式后再通过此函数写入DDIC
            }
            catch
            {
                MessageBox.Show("Gamma数据更新错误！", "唐韬说：");
            }
        }
        private void numStep_ValueChanged(object sender, EventArgs e)   //手动调整AutoGamma调节步长以在初次调整Gamma是提升速度
        {
            rstep = (byte)(int.Parse(numStep.Value.ToString()));
            gstep = (byte)(int.Parse(numStep.Value.ToString()));
            bstep = (byte)(int.Parse(numStep.Value.ToString()));
        }


        #region  //Gamma调整计时
        System.DateTime TimeNow = new DateTime();
        TimeSpan TimeCount = new TimeSpan();
        private void TimTest_Tick(object sender, EventArgs e)
        {
            TimeCount = DateTime.Now - TimeNow;
            txtTimeShow.Text = string.Format("{0:00}:{1:00}:{2:00}", TimeCount.Hours, TimeCount.Minutes, TimeCount.Seconds);
        }
        #endregion
        private byte[] arrbyte_tmp = new byte[250];         //临时保存下位机返回值
        public void DataGirdShow(byte index, double RRR, double GGG, double BBB)        //UI 表格显示 R/G/B对应Gamma寄存器值
        {
            int Row_Accum = 0, Current_Index = 0, Row_flag = 0;

            DataGridViewRow Row1 = new DataGridViewRow();

            Row_Accum = this.GammaReg_dataGridView.Rows.Count - 1;
            if (Row_Accum != 0)
            {
                Current_Index = this.GammaReg_dataGridView.SelectedCells[0].RowIndex;
                if ((Current_Index != Row_Accum - 1) && (Current_Index != Row_Accum))
                {
                    Row_Accum = Current_Index;
                    Row_flag = 1;
                }
                else
                {
                    this.GammaReg_dataGridView.Rows.Add(Row1);
                }
                if ((Row_Accum != 0) && (Row_flag != 1))
                {
                    if (Current_Index != Row_Accum)
                    {
                        this.GammaReg_dataGridView.Rows[Row_Accum - 1].Selected = false;
                        this.GammaReg_dataGridView.Rows[Row_Accum].Selected = true;
                    }
                }
            }
            else
            {
                this.GammaReg_dataGridView.Rows.Add(Row1);
            }
            this.GammaReg_dataGridView.Rows[Row_Accum].Cells[0].Value = index + 1;//序号
            //Rows[x]为第x行,Cells[x]为第x列
            this.GammaReg_dataGridView.Rows[Row_Accum].Cells[1].Value = (D_lum[index]).ToString("#0.0000");
            this.GammaReg_dataGridView.Rows[Row_Accum].Cells[2].Value = RRR;
            this.GammaReg_dataGridView.Rows[Row_Accum].Cells[3].Value = GGG;
            this.GammaReg_dataGridView.Rows[Row_Accum].Cells[4].Value = BBB;

            if (Row_flag == 1)
            {
                Row_flag = 0;
                Row_Accum = this.GammaReg_dataGridView.Rows.Count - 1;
                this.GammaReg_dataGridView.Rows[Current_Index].Selected = false;
                this.GammaReg_dataGridView.Rows[Row_Accum - 1].Selected = true;
            }
            GammaReg_dataGridView.FirstDisplayedScrollingRowIndex = GammaReg_dataGridView.RowCount - 1;
        }

        #endregion  //--- Auto Gamma-----
        #region //通用命令处理
        private void Send_Cmd_Click(object sender, EventArgs e)
        {
            Button btn = (Button)sender;
            switch (btn.Name)
            {
                case "btnSend1":
                    {
                        frmTop.txtProcessDrivercode(txtCmd1.Text, out string txtbaseClearOriginal, out string txtMCleatOriginal);
                    }
                    break;
                case "btnSend2":
                    {
                        frmTop.txtProcessDrivercode(txtCmd2.Text, out string txtbaseClearOriginal, out string txtMCleatOriginal);
                    }
                    break;
                case "btnSend3":
                    {
                        frmTop.txtProcessDrivercode(txtCmd3.Text, out string txtbaseClearOriginal, out string txtMCleatOriginal);
                    }
                    break;

            }
            Setting.TempRecord.cmdLen = 6;
            if (rBt_LP_DCS_Long_Write.Checked | rBt_LP_DCS_Short_Write.Checked | rBt_LP_Gerneric_Long_Write.Checked | rBt_LP_Gerneric_Short_Write.Checked)
            {
                frmTop.SendCmd(0);
            }
            else
            {
                frmTop.SendCmd(4);
            }
            txttip.Text += "命令已下发...\r\n";
            txttip.Select(txttip.Text.Length, 0);
            txttip.ScrollToCaret();
        }
        private void Send_Cmd_Demuura_Click(object sender, EventArgs e)
        {
            Button btn = (Button)sender;
            bool Send_en = true;
            switch (btn.Name)
            {
                case "btnSend_1": //1.Flash ID
                    {
                        frmTop.Generate_textBox.Text = btnSend_Text1.Text;
                        frmTop.Generate_File_Click(frmTop.Generate_File_Run, e);
                        Send_en = false;
                    }
                    break;
                case "btnSend_2"://2.Check Flash 
                    {
                        frmTop.txtProcessDrivercode(btnSend_Text2.Text, out string txtbaseClearOriginal, out string txtMCleatOriginal);
                    }
                    break;
                case "btnSend_3"://3.Flash Program
                    {
                        frmTop.txtProcessDrivercode(btnSend_Text3.Text, out string txtbaseClearOriginal, out string txtMCleatOriginal);
                    }
                    break;
                case "btnSend_4"://4.Check CRC
                    {
                        frmTop.Generate_textBox.Text = btnSend_Text4.Text;
                        frmTop.Generate_File_Click(frmTop.Generate_File_Run, e);
                        Send_en = false;
                    }
                    break;
                case "btnSend_5"://Demura ON
                    {
                        frmTop.Generate_textBox.Text = btnSend_Text5.Text;
                        frmTop.Generate_File_Click(frmTop.Generate_File_Run, e);
                        Send_en = false;
                    }
                    break;
                case "btnSend_6"://Demura OFF
                    {
                        frmTop.Generate_textBox.Text = btnSend_Text6.Text;
                        frmTop.Generate_File_Click(frmTop.Generate_File_Run, e);
                        Send_en = false;
                    }
                    break;
                case "button_SD5306_1"://SD5306 Flash Program
                    {
                        frmTop.txtProcessDrivercode(btnSend_SD5306_1.Text, out string txtbaseClearOriginal, out string txtMCleatOriginal);
                    }
                    break;
                case "button_SD5306_2"://SD5306  Check CRC
                    {
                        frmTop.Generate_textBox.Text = btnSend_SD5306_2.Text;
                        frmTop.Generate_File_Click(frmTop.Generate_File_Run, e);
                        Send_en = false;
                    }
                    break;
                case "button_SD5501_1"://SD5501擦除
                    {
                        frmTop.Generate_textBox.Text = btnSend_SD5501_1.Text;
                        frmTop.Generate_File_Click(frmTop.Generate_File_Run, e);
                        Send_en = false;
                    }
                    break;
                case "button_SD5501_2"://SD5501
                    {
                        frmTop.Generate_textBox.Text = btnSend_SD5501_2.Text;
                        frmTop.Generate_File_Click(frmTop.Generate_File_Run, e);
                        Send_en = false;
                    }
                    break;
                case "button_SD5501_3"://SD5501
                    {
                        frmTop.Generate_textBox.Text = btnSend_SD5501_3.Text;
                        frmTop.Generate_File_Click(frmTop.Generate_File_Run, e);
                        Send_en = false;
                    }
                    break;
                case "button_SD5501_4"://SD5501
                    {
                        frmTop.Generate_textBox.Text = btnSend_SD5501_4.Text;
                        frmTop.Generate_File_Click(frmTop.Generate_File_Run, e);
                        Send_en = false;
                    }
                    break;

            }
            Setting.TempRecord.cmdLen = 6;
            if (Send_en == true)
            {
                if (rBt_LP_DCS_Long_Write.Checked | rBt_LP_DCS_Short_Write.Checked | rBt_LP_Gerneric_Long_Write.Checked | rBt_LP_Gerneric_Short_Write.Checked)
                {
                    frmTop.SendCmd(0);
                }
                else
                {
                    frmTop.SendCmd(4);
                }
            }
            txttip.Text += "命令已下发...\r\n";
            txttip.Select(txttip.Text.Length, 0);
            txttip.ScrollToCaret();
        }

        private void SaveCode_Click(object sender, EventArgs e)
        {
            SaveFileDialog txt = new SaveFileDialog();
            txt.Filter = @"txt文件(*.txt)|*.txt|所有文件(*.*)|*.*";
            string str = "//-----保存Driver IC Code文件------\r\n";
            if (txt.ShowDialog() == DialogResult.OK)
            {
                if (txt.FileName == " ")
                {
                    return;
                }
                StreamWriter sw = null; //文件流
                sw = new StreamWriter(txt.FileName, false, Encoding.GetEncoding("UTF-8"));//Encoding.GetEncoding("UTF-8")
                try
                {
                    if (ChkCMD1.Checked)
                    {
                        str += "//---CMD1---\r\n" + txtCmd1.Text;// lstMIPIDriver.Items[i].ToString();
                        str += "\r\n\r\n";
                    }
                    if (ChkCMD2.Checked)
                    {
                        str += "//---CMD2---\r\n" + txtCmd2.Text;// lstMIPIDriver.Items[i].ToString();
                        str += "\r\n\r\n";
                    }
                    if (ChkCMD3.Checked)
                    {
                        str += "//---CMD3---\r\n" + txtCmd3.Text;// lstMIPIDriver.Items[i].ToString();
                        str += "\r\n\r\n";
                    }
                    sw.Write(str);
                    sw.Dispose(); //释放资源
                    sw.Close(); //关闭数据流
                    MessageBox.Show("Driver IC Code保存OK！", "系统提示：");
                }
                catch
                {
                    MessageBox.Show("Driver IC Code保存时发生错误，请再试！", "系统提示：");
                }
            }
        }
        private void OpenTxtCode_Click(object sender, EventArgs e)
        {
            Button btn = (Button)sender;

            OpenFileDialog of = new OpenFileDialog();
            of.Filter = "文本文件(*.txt)|*.txt|所有文件(*.*)|*.*";
            of.Title = "初始化 Code";

            if (of.ShowDialog() == DialogResult.OK)
            {
                StreamReader streamReader = new StreamReader(of.FileName, Encoding.Default);
                switch (btn.Name)
                {
                    case "OpenTxtCode":
                        {
                            txtCmd1.Clear();
                            txtCmd1.Text = streamReader.ReadToEnd();
                        }
                        break;
                    case "OpenTxtCode2":
                        {
                            txtCmd2.Clear();
                            txtCmd2.Text = streamReader.ReadToEnd();
                        }
                        break;
                    case "OpenTxtCode3":
                        {
                            txtCmd3.Clear();
                            txtCmd3.Text = streamReader.ReadToEnd();
                        }
                        break;

                    default: break;
                }
                streamReader.Close();
            }
        }
        #endregion
        string path = "";
        #region //------自定义功能按键---------------


        private void Gamma51set(object sender, EventArgs e)
        {

        }

        //------------------------------------------------------------

        private void SD4202_Gamma_FormClosing(object sender, FormClosingEventArgs e)
        {
            e.Cancel = true;
            this.Hide();
        }


        #endregion
        #region    //浏览图片
        //string path = "";
        private void btnBrowsePic_Click(object sender, EventArgs e)    //载入画面按键  选择文件夹
        {
            if (txtbmp.Text != "")
            {
                frmTop.defaultfilePath = txtbmp.Text;
            }
            else
            {
                StreamReader streamReader = new StreamReader("./update/Picaddr.txt", Encoding.Default);
                frmTop.defaultfilePath = streamReader.ReadLine();
                streamReader.Close();
            }
            FolderBrowserDialog fldb = new FolderBrowserDialog();
            //首次defaultfilePath为空，按FolderBrowserDialog默认设置（即桌面）选择            
            if (frmTop.defaultfilePath != "")
            {
                //设置此次默认目录为上一次选中目录
                fldb.SelectedPath = frmTop.defaultfilePath;
            }

            fldb.ShowNewFolderButton = false;
            DialogResult res = fldb.ShowDialog();
            if (res != System.Windows.Forms.DialogResult.OK)
            {
                MessageBox.Show("没选择任何文件夹.");
                return;
            }
            frmTop.defaultfilePath = fldb.SelectedPath;
            path = fldb.SelectedPath;
            if (!Directory.Exists(path))
            {
                MessageBox.Show("文件夹不存在.");
                return;
            }
            DirectoryInfo di = new DirectoryInfo(path);
            this.listBox3_BMPFile.Items.Clear();
            this.CreateListItem(di);//递归加载文件夹里的所有图片
            txtbmp.Text = path;
            // -------------------------------------------------------------------------
            StreamWriter sw = null; //文件流
            sw = new StreamWriter("./update/Picaddr.txt", false, Encoding.Default);//Encoding.GetEncoding("UTF-8")
            sw.Write(frmTop.defaultfilePath);
            sw.Dispose(); //释放资源
            sw.Close(); //关闭数据流
        }
        /// <summary>
        /// 递归文件夹，把文件夹里所有后缀类似图片的文件，加入listbox
        /// </summary>
        /// <param name="di"></param>
        private void CreateListItem(DirectoryInfo di)
        {
            foreach (DirectoryInfo childDi in di.GetDirectories())
            {
                this.CreateListItem(childDi);
            }

            foreach (FileInfo fi in di.GetFiles())
            {
                if (ImageType.Contains(fi.Extension))//找到一个图片(如果用户手贱把一个excel文件后缀改成jpeg没办法)
                {
                    this.listBox3_BMPFile.Items.Add(new MyImage(fi.FullName));
                }
            }
        }

        private void btnReadGamma_Click(object sender, EventArgs e)
        {
            Send_buf = new byte[6];
            Send_buf[0] = 0x74;
            Send_buf[1] = 0x01;
            Send_buf[2] = 0x01;
            this.GammaReg_dataGridView.Rows.Clear();
            if (NormalGamma.Checked)
            {
                Send_buf[3] = 0x01;
            }
            else if (HBMGamma.Checked)
            {
                Send_buf[3] = 0x02;
            }
            else if (AODGamma.Checked)
            {
                Send_buf[3] = 0x03;
            }
            CRCData.CalculateCrc16Start_Length(Send_buf, 0, 4, out Send_buf[4], out Send_buf[5]);
            try
            {
                frmTop.comPort.Write(Send_buf, 0, 6);
            }
            catch
            {
                MessageBox.Show("串口有误，请检查", "错误");
            }

        }

        private void lstImage_Click(object sender, EventArgs e)
        {
            if (listBox3_BMPFile.SelectedItem == null)
            {
                return;
            }
            MyImage selectedImg = (MyImage)listBox3_BMPFile.SelectedItem;
            Image img = new Bitmap(selectedImg.Path);
            pictureBox1.Image = img;
        }
        private byte ircbmpflag = 1;

        public class MyImage
        {
            public MyImage(string p)
            {
                this.Path = p;
            }
            public string Path { get; set; }
            public override string ToString()
            {
                if (Path == null)
                {
                    return null;
                }
                return System.IO.Path.GetFileName(this.Path);
            }
        }
        //-----------------------------------------
        #endregion


    }
}
